package com.compass.doctor.ui.patient

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnAddExaminationCallBack
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.databinding.ActivityExaminationBinding
import com.compass.doctor.dialog.DrugInfoDialog
import com.compass.doctor.dialog.InspectionListDialog
import com.compass.doctor.ui.patient.fragment.ExamineFragment
import com.compass.doctor.ui.patient.fragment.InspectFragment
import com.compass.doctor.ui.patient.viewmodel.ExamineViewModel
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.framework.adapter.ViewPage2FragmentAdapter
import com.compass.framework.constant.KEY_DRUG_LIST
import com.compass.framework.constant.KEY_SESSION_ID
import com.compass.framework.constant.KEY_PATIENT_ID
import com.compass.framework.constant.REFRESH_EXAMINE
import com.compass.framework.constant.REFRESH_PATIENT
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toBeanOrNull
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.CreateInspection
import com.compass.framework.model.CreateInspectionWarp
import com.compass.framework.model.Dictionaries
import com.compass.framework.model.Drug
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.getDrawableResource

/**
 * Description： 创建检验检查
 * Date:2023/12/19 16:37
 */
class ExaminationActivity : BaseVBActivity<ActivityExaminationBinding>() {


    companion object {
        fun start(context: Context, patientId: String, sessionId: String) {
            val intent = Intent(context, ExaminationActivity::class.java)
            intent.putExtra(KEY_PATIENT_ID, patientId)
            intent.putExtra(KEY_SESSION_ID, sessionId)
            context.startActivity(intent)
        }
    }

    private lateinit var viewPageAdapter: ViewPage2FragmentAdapter
    private var fragments: ArrayList<Fragment> = ArrayList()

    private lateinit var inspectFragment: InspectFragment
    private lateinit var examineFragment: ExamineFragment
    private val examineViewModel: ExamineViewModel by viewModels()
    private val patientViewModel: PatientViewModel by viewModels()
    private lateinit var patientId: String//患者ID
    private lateinit var sessionId: String//患者云信账号
    private var toIndex = 0//1检验 2检查
    override fun initView(savedInstanceState: Bundle?) {

        mBinding.dslTab.tabIndicator.indicatorWidth = -2
        mBinding.dslTab.tabIndicator.indicatorEnableFlow = true
        mBinding.dslTab.configTabLayoutConfig {
            onSelectIndexChange = { _, selectIndexList, _, _ ->
                toIndex = selectIndexList.first()
                mBinding.viewpager2.setCurrentItem(toIndex, false)
            }
        }
        viewPageAdapter = ViewPage2FragmentAdapter(supportFragmentManager, lifecycle, fragments)
        mBinding.viewpager2.adapter = viewPageAdapter
        mBinding.viewpager2.isUserInputEnabled = false//禁止viewPage滑动
        mBinding.viewpager2.setCurrentItem(0, false)

    }

    override fun initData() {
        patientId = intent.serializable(KEY_PATIENT_ID)!!
        sessionId = intent.serializable(KEY_SESSION_ID)!!
        showLoading()
        patientViewModel.getPatientDetails(patientId)
        patientViewModel.patientDetailsLiveData.observe(this) {
            it?.let {
                mBinding.ivHead.setUrlCircle(it.avatar)

                mBinding.tvName.text = it.name
                mBinding.ivSex.background =
                    if (it.sex == 1) getDrawableResource(R.mipmap.icon_male) else getDrawableResource(
                        R.mipmap.icon_female
                    )
                mBinding.tvAge.text = it.patientAge
            }
            dismissLoading()
        }
        examineViewModel.createInspectionLiveData.observe(this) {
            dismissLoading()
            it?.let {
                UserInfoManager.saveExaminationInspectionJson(null)
                LiveDataBus.get().with(REFRESH_EXAMINE).postValue(REFRESH_EXAMINE)
                showToast("开具成功")
                finish()
            }
        }
        initFragment()
        setExaminationInspection()
    }


    private var inspectionList: ArrayList<CreateInspection> = ArrayList()//已添加的检验检查
    private var onExaminationCallBack = object : OnAddExaminationCallBack {
        override fun onExaminationCallBack(inspection: CreateInspection) {
            inspectionList.add(inspection)
            setTips()
        }
    }

    private var drugInfoDialog: InspectionListDialog.Builder? = null
    private var onSubmitCallBack = object : OnCustomButtonClick {
        override fun onButtonCallBack(position: Int, msgType: String?) {
            when (msgType) {
                "delete" -> {
                    setTips()
                }

                "submit" -> {
                    submit()
                }

            }

        }
    }

    override fun intListener() {
        mBinding.tvAddExamination.onClick {
            when (toIndex) {
                0 -> {
                    inspectFragment.createInspection()
                }

                1 -> {
                    examineFragment.createInspection()
                }
            }

        }
        mBinding.llLook.onClick {
            drugInfoDialog = InspectionListDialog.Builder(this, inspectionList, onSubmitCallBack)
            drugInfoDialog?.show()

        }
        mBinding.tvSubmit.onClick {
            submit()
        }
    }


    private fun submit() {
        if (inspectionList.isNotEmpty()) {
            showLoading()
            examineViewModel.createInspection(CreateInspectionWarp(inspectionList))

        } else {
            showToast("请先添加检验或检查")
        }

    }


    private fun setExaminationInspection(){
        val list = UserInfoManager.getExaminationInspectionJson()?.toBeanOrNull<ArrayList<CreateInspection>>()
        list?.let {
            inspectionList=it
            setTips()
        }
    }


    private fun setTips() {
        UserInfoManager.saveExaminationInspectionJson(inspectionList.toJson())
        var drugNumber = inspectionList.size.toString()
        if (drugNumber == "0") {
            mBinding.imgMessage.gone()
        } else {
            mBinding.imgMessage.text = drugNumber
            mBinding.imgMessage.visible()
        }
        mBinding.tvDrugsNumber.text = "共${drugNumber}项"


    }

    private fun initFragment() {
        //set fragment
        inspectFragment = InspectFragment()
        val bundleIn = Bundle()
        bundleIn.putString(KEY_SESSION_ID, sessionId)
        bundleIn.putString(KEY_PATIENT_ID, patientId)
        inspectFragment.arguments = bundleIn
        inspectFragment.setOnExaminationCallBack(onExaminationCallBack)
        fragments.add(inspectFragment)

        examineFragment = ExamineFragment()
        val bundleEx = Bundle()
        bundleEx.putString(KEY_SESSION_ID, sessionId)
        bundleEx.putString(KEY_PATIENT_ID, patientId)
        examineFragment.arguments = bundleEx
        examineFragment.setOnExaminationCallBack(onExaminationCallBack)
        fragments.add(examineFragment)

    }
}